import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter_study_2025/httptest/user_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';

class HttpUtil {
  static final HttpUtil _instance = HttpUtil._internal();
  late Dio dio;

  factory HttpUtil() => _instance;

  HttpUtil._internal() {
    BaseOptions options = BaseOptions(
      baseUrl: 'https://api.misstory789.online/api/asf/',
      connectTimeout: const Duration(seconds: 5),
      receiveTimeout: const Duration(seconds: 3),
      contentType: 'application/json-patch+json',
      validateStatus: (status) => status != null,
    );
    dio = Dio(options);

    dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) {
          Future<String?> token = _getToken();
          options.headers['Authorization'] = 'Bearer $token';
          return handler.next(options);
        },
        onError: (DioException e, handler) {
          _handleError(e);
          return handler.next(e);
        },
      ),
    );
  }

  Future<String?> _getToken() async {
    return UserManager.getCurrentToken();
  }

  void _handleError(DioException e) {
    switch (e.type) {
      case DioExceptionType.connectionTimeout:
        print('连接超时');
        break;
      case DioExceptionType.badResponse:
        print('服务器错误: ${e.response?.statusCode}');
        break;
      default:
        print('请求错误: ${e.message}');
    }
  }

  // ------------------------------
  // 1. 泛型解析版本（自动转为模型对象）
  // ------------------------------

  /// 泛型GET请求（返回解析后的模型对象）
  Future<BaseResponse<T>?> getModel<T>(
    String path, {
    Map<String, dynamic>? params,
    required T Function(dynamic) fromJson,
  }) async {
    try {
      Response response = await dio.get(path, queryParameters: params);
      if (response.data is Map) {
        return BaseResponse.fromJson(
          response.data as Map<String, dynamic>,
          fromJson,
        );
      }
    } on DioException catch (e) {
      print('GET模型请求错误: ${e.message}');
    }
    return null;
  }

  /// 泛型POST请求（返回解析后的模型对象）
  Future<BaseResponse<T>?> postModel<T>(
    String path, {
    dynamic data,
    Map<String, dynamic>? params,
    required T Function(dynamic) fromJson,
  }) async {
    try {
      Response response = await dio.post(
        path,
        data: data,
        queryParameters: params,
      );
      print("response = %=$response");
      if (response.data is Map) {
        return BaseResponse.fromJson(
          response.data as Map<String, dynamic>,
          fromJson,
        );
      }
    } on DioException catch (e) {
      print('POST模型请求错误: ${e.message}');
    }
    return null;
  }

  // ------------------------------
  // 2. 非泛型版本（返回原始JSON数据）
  // ------------------------------

  /// 普通GET请求（返回原始JSON数据）
  Future<Map<String, dynamic>?> getJson(
    String path, {
    Map<String, dynamic>? params,
  }) async {
    try {
      Response response = await dio.get(path, queryParameters: params);
      if (response.data is Map) {
        return response.data as Map<String, dynamic>;
      }
    } on DioException catch (e) {
      print('GET原始请求错误: ${e.message}');
    }
    return null;
  }

  /// 普通POST请求（返回原始JSON数据）
  Future<Map<String, dynamic>?> postJson(
    String path, {
    dynamic data,
    Map<String, dynamic>? params,
  }) async {
    try {
      Response response = await dio.post(
        path,
        data: data,
        queryParameters: params,
      );
      if (response.data is Map) {
        return response.data as Map<String, dynamic>;
      }
    } on DioException catch (e) {
      print('POST原始请求错误: ${e.message}');
    }
    return null;
  }
}

// 基础响应模型
class BaseResponse<T> {
  final int status;
  final String message;
  final T? result;

  BaseResponse({required this.status, required this.message, this.result});

  // 从JSON解析
  factory BaseResponse.fromJson(
    Map<String, dynamic> json,
    T Function(dynamic) fromJson,
  ) {
    return BaseResponse(
      status: json['status'] as int,
      message: json['message'] as String,
      result: json['result'] != null ? fromJson(json['result']) : null,
    );
  }
}

// 解析工具类
class JsonParser {
  // 将JSON字符串解析为指定类型
  static T? fromJson<T>(String jsonString, T Function(dynamic) fromJson) {
    try {
      final jsonMap = json.decode(jsonString);
      return fromJson(jsonMap);
    } catch (e) {
      print('JSON解析错误: $e');
      return null;
    }
  }

  // 将JSON Map解析为指定类型
  static T? fromJsonMap<T>(
    Map<String, dynamic> jsonMap,
    T Function(dynamic) fromJson,
  ) {
    try {
      return fromJson(jsonMap);
    } catch (e) {
      print('JSON Map解析错误: $e');
      return null;
    }
  }
}

class LoginTokenModel {
  final String? token;
  final String? tokenType;
  final String? refreshToken;
  final String? expired;
  final String? refreshExpired;

  LoginTokenModel({
    this.token,
    this.tokenType,
    this.refreshToken,
    this.expired,
    this.refreshExpired,
  });

  factory LoginTokenModel.fromJson(dynamic json) {
    return LoginTokenModel(
      token: json['token']?.toString(),
      tokenType: json['tokenType']?.toString(),
      refreshToken: json['refreshToken']?.toString(),
      expired: json['expired']?.toString(),
      refreshExpired: json['refreshExpired']?.toString(),
    );
  }
}

/**
 
// 使用示例
class User {
  final String id;
  final String name;

  User({required this.id, required this.name});

  static User fromJson(dynamic json) {
    return User(
      id: json['id'] as String,
      name: json['name'] as String,
    );
  }
}

// 调用示例
void requestExamples() async {
  // 1. 使用泛型版本（获取模型对象）
  final userResponse = await HttpUtil().getModel(
    '/user/profile',
    params: {'id': '123'},
    fromJson: User.fromJson,
  );
  if (userResponse?.status == 0) {
    print('用户名: ${userResponse?.data?.name}'); // 直接访问模型属性
  }

  // 2. 使用非泛型版本（获取原始JSON）
  final rawResponse = await HttpUtil().postJson(
    '/login',
    data: {'username': 'test', 'password': '123'},
  );
  if (rawResponse?['status'] == 0) {
    print('登录成功: ${rawResponse?['message']}'); // 手动处理JSON
  }
}

 */
